﻿using AutoMapper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mes.Pendant.Common.DtoMapping
{
	/// <summary>
	/// 封装全局类型映射-扩展对象
	/// </summary>
	public static class AutoMapperExt
	{
		//这里是没有用好的

		/// <summary>
		///  类型映射
		/// </summary>
		public static T MapTo<T>(this object obj)
		{
			if (obj == null) return default;

			////var config = new MapperConfiguration(m => m.CreateMap<User, UserDto>());
			//var mapper = config.CreateMapper();
			//var userDto = mapper.Map<UserDto>(user);

			var config = new MapperConfiguration(m => m.CreateMap(obj.GetType(), typeof(T)));
			var mapper = config.CreateMapper();
			return mapper.Map<T>(obj);
		}

		/// <summary>
		/// 集合列表类型映射 
		/// </summary>
		public static List<T> MapToList<T>(this IEnumerable obj)
		{
			Type sourceType = obj.GetType().GetGenericArguments()[0];  //获取枚举的成员类型
			var config = new MapperConfiguration(cfg => cfg.CreateMap(sourceType, typeof(T)));
			var mapper = config.CreateMapper();
			return mapper.Map<List<T>>(obj);
		}

		/// <summary>
		/// 集合列表类型映射
		/// </summary>
		public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
		{
			var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(TSource), typeof(TDestination)));
			var mapper = config.CreateMapper();

			return mapper.Map<List<TDestination>>(source);
		}

		/// <summary>
		/// 类型映射
		/// </summary>
		public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
			where TSource : class
			where TDestination : class
		{
			if (source == null) return destination;

			var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(TSource), typeof(TDestination)));
			var mapper = config.CreateMapper();
			return mapper.Map<TDestination>(source);
		}

	}

}
